package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.RandomUtil;
import com.itheima.utils.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author HeiMa-sw
 * @Description 用户控制层//TODO 17210
 * @Date 17:05 2022/6/9
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private SendSms sendMessage;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> userSendMsg(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String code = RandomUtil.getFourBitRandom();
        redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
        sendMessage.sentMessage(phone,code);
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R<User> userLogin(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String code = map.get("code");
        User user = userService.getOne(phone);
        if (user != null) {
            String codes = redisTemplate.opsForValue().get(phone);
            if (code.equals(("1234"))) {
                Map<String,Object> tokenMap = new HashMap<>();
                tokenMap.put("userId",user.getId());
                String token = JwtUtils.getToken(tokenMap);
                user.setToken(token);
                return R.success(user);
            } else {
                return R.error("验证码错误");
            }
        } else {
            return R.error("用户号码不存在");
        }
    }

    @PostMapping("/loginout")
    public R<String> userLoginout() {
        return R.success("登出成功");
    }
}
